package com.bys.controller;

import com.bys.entity.User;
import com.bys.service.IUserService;
import com.bys.vo.UserVo;
import org.example.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.example.util.PageResult;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bys
 * @since 2025-01-07
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @RequestMapping("/list")
    public R findAll(){
        return R.ok().data("users",userService.list());
    }
    @GetMapping("/findByPage/{page}/{pageSize}")
    public R findByPage(@PathVariable("page") Integer page,
                        @PathVariable("pageSize") Integer pageSize){
        PageResult<User> users = userService.findByPage(page,pageSize);
        System.out.println(users);
        return R.ok().data("users",users);
    }
    @PostMapping("/search/{page}/{pageSize}")
    public R search(@PathVariable("page") Integer page,
                    @PathVariable("pageSize") Integer pageSize,
                    @RequestBody(required = false) UserVo vo){
        PageResult<User> users = userService.search(page,pageSize,vo);
        return R.ok().data("users",users);
    }
    @PostMapping("/save")
    public R saveUser(@RequestBody User user){
        return userService.save(user) ? R.ok().message("添加成功！") : R.error().message("添加失败！");
    }
    @PutMapping("/update")
    public R updateUser(@RequestBody User user){
        return userService.updateById(user) ? R.ok().message("添加成功！") : R.error().message("添加失败！");
    }
    @DeleteMapping("/delete/{ids}")
    public R deleteUser(@PathVariable("ids") String ids){  // 1,2,3
        String[] split = ids.split(",");
        List<String> uids = Arrays.asList(split);
        System.out.println(uids);
        return userService.removeByIds(uids) ? R.ok().message("删除学生成功!") : R.error().message("删除学生失败!");
    }
}
